package org.mte.swift.jqgrid;

import java.io.Serializable;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;

/**
 * JQGridService
 */
@Service("jqgrid")
public class JQGridServiceImpl implements JQGridService {
	
	private Sort currentSort = null;
	
	public PageRequest prepare(Integer pageNumber, Integer rows, String sortBy, String order) {
		Sort sort = currentSort;
		if (sortBy != null && !sortBy.equals("") && 
				order != null && !order.equals("")) {
			if (order.equals("desc")) {
				sort = new Sort(Sort.Direction.DESC, sortBy);
			} else {
				sort = new Sort(Sort.Direction.ASC, sortBy);
			}
			currentSort = sort;
		}
		// Constructs page request for current page
		// Note: page number for Spring Data JPA starts with 0, while jqGrid starts with 1			
		PageRequest pageRequest = new PageRequest(pageNumber - 1, rows, sort);
		
/*		PageRequest pageRequest = null;
		if (sort != null) {
			pageRequest = new PageRequest(pageNumber - 1, rows, sort);
		} else {
			pageRequest = new PageRequest(pageNumber - 1, rows);
		}*/
		return pageRequest;
	}

	public <T extends Serializable> void update(Page<T> page, JQGridResponse<T> gridResponse) {
		gridResponse.setPage(page.getNumber() + 1);
		gridResponse.setTotal(page.getTotalPages());
		gridResponse.setRecords(page.getTotalElements());	
		gridResponse.setRows(Lists.newArrayList(page.iterator()));
	}
}